package com.robot.botrunning.utils;

import com.robot.botrunning.pojo.Robot;
import org.codehaus.commons.compiler.CompileException;
import org.codehaus.janino.SimpleCompiler;
import org.joor.Reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

@Component
public class runningCode extends Thread{//执行代码，每次执行都创建一个函数
    private Robot robot;
    public static RestTemplate restTemplate;
    @Autowired
    public void setRestTemplate(RestTemplate restTemplate){
        runningCode.restTemplate = restTemplate;
    }
    private final static String receiveDirectionURL = "http://127.0.0.1:3000/receiveDirecion/";
    public void startTimeOut(long timeout, Robot robot){
        this.robot = robot;
        this.start();
        try {
            this.join(timeout);//最多执行timeout秒，如果执行完成，提前结束
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.interrupt();//如果超时，中断当前线程
    }
    private String addUid(String code, String uid) {  // 在code中的Bot类名后添加uid,相同类名只执行一次
        int k = code.indexOf(" implements com.robot.botrunning.utils.botInterface");
        return code.substring(0,k) + uid + code.substring(k);
    }
    @Override
    public void run() {
        System.out.println("开始执行代码");
        if(robot.getLang().equals("java")){
            UUID uuid = UUID.randomUUID();
            String rand = uuid.toString().substring(0,8);
            String code=robot.getBotCode();
            SimpleCompiler compiler = new SimpleCompiler();

            try {
                compiler.cook(code);
            } catch (CompileException e) {
                throw new RuntimeException(e);
            }
            Class<?> clazz = null;
            try {
                clazz = compiler.getClassLoader().loadClass("game");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

            int d = Reflect.on(clazz)
                    .create()     // 创建实例
                    .call("nextMove",robot.getMap(),robot.getMyX(),robot.getMyY(),robot.getOppoX(),robot.getOppoY(),robot.getSteps()) // 调用方法
                    .get();       // 获取结果
//            botInterface botInterface = Reflect.compile(
//                    "com.robot.botrunning.utils.test"+rand,
//                    addUid(robot.getBotCode(),rand)
//            ).create().get();//编译java代码
//            System.out.println(botInterface);
//            int d = botInterface.nextMove(robot.getMap(),robot.getMyX(),robot.getMyY(),robot.getOppoX(),robot.getOppoY(),robot.getSteps());//将返回值作为方向，然后传回主程序
//            System.out.println("给出方向"+d);
            MultiValueMap<String,String> map = new LinkedMultiValueMap<>();
            map.add("d",String.valueOf(d));
            map.add("uid", String.valueOf(robot.getUserid()));
            restTemplate.postForObject(receiveDirectionURL,map,String.class);
        }
        else if(robot.getLang().equals("cpp") || robot.getLang().equals("c_cpp")){

//            try {
//                Files.writeString(Path.of("/www/wwwroot/cpp/main.cpp"), robot.getBotCode());
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
            //写c++文件
            try (BufferedWriter bw = new BufferedWriter(new FileWriter("/www/wwwroot/cpp/main.cpp", true))) {
                bw.write(robot.getBotCode());
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String stringg = Arrays.deepToString(robot.getMap());//地图转字符串
            stringg = stringg.replaceAll("[\\s,\\[\\]]", "");
            String stringsteps = Arrays.toString(robot.getSteps());
            stringsteps=stringsteps.replaceAll("[\\s,\\[\\]]", "");
            Process process = null;
            String[] cmd = { "sh", "/www/wwwroot/cpp/test.sh",stringg, String.valueOf(robot.getMyX()),String.valueOf(robot.getMyY()),String.valueOf(robot.getOppoX()),String.valueOf(robot.getOppoY()),stringsteps, String.valueOf(robot.getUserid())};
            try {
                process = Runtime.getRuntime().exec(cmd);//执行调用
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        else if(robot.getLang().equals("c")){
            try (BufferedWriter bw = new BufferedWriter(new FileWriter("/www/wwwroot/c/main.c", true))) {
                bw.write(robot.getBotCode());
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String stringg = Arrays.deepToString(robot.getMap());//地图转字符串
            stringg = stringg.replaceAll("[\\s,\\[\\]]", "");
            String stringsteps = Arrays.toString(robot.getSteps());
            stringsteps=stringsteps.replaceAll("[\\s,\\[\\]]", "");
            Process process = null;
            try {
                String[] cmd = { "sh", "/www/wwwroot/c/test.sh",stringg, String.valueOf(robot.getMyX()),String.valueOf(robot.getMyY()),String.valueOf(robot.getOppoX()),String.valueOf(robot.getOppoY()),stringsteps, String.valueOf(robot.getUserid())};
                process = Runtime.getRuntime().exec(cmd);//执行调用
                int exitCode = process.waitFor();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream())
                );

                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("[输出] " + line);
                }
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else if(robot.getLang().equals("python")){
            Path filePath = Paths.get("/www/wwwroot/python/main.py");
//            String newContent = "def nextMove(map,myX,myY,oppoX,oppoY,steps):\n" +
//                    "    return 0\n\n" ;
            String newContent = robot.getBotCode();
            try {
                // 读取原文件内容
                String originalContent = Files.readString(filePath);

                // 拼接新内容 + 原内容
                String fullContent = newContent + originalContent;

                // 覆盖写入文件
                Files.writeString(filePath, fullContent);

            } catch (IOException e) {
                e.printStackTrace();
            }
            String[] cmd = { "sh", "/www/wwwroot/python/test.sh", Arrays.deepToString(robot.getMap()).replaceAll("\\s+", ""),"myx","myy","oppox","oppoy", Arrays.toString(robot.getSteps()).replaceAll("\\s+", ""), String.valueOf(robot.getUserid())};
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(cmd);//执行调用
                String line;
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream())
                );
                while ((line = reader.readLine()) != null) {
                    System.out.println("[输出] " + line);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("代码执行完成");
    }
}
